package com.example.util;

import com.example.user.entity.User;
import lombok.val;
import sun.security.util.Password;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 贾明祯
 * @ClassName PasswordUtil
 * @Date 2020/8/17 8:56
 * @Introduce 密码类
 */
public class PasswordUtil implements Serializable{

    private static final String[] PASSWORDSTRING = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    /**
     * @Author: 贾明祯
     * @Date: 2020/8/17 9:03
     * @introduce: 获取6位字符串的盐
     */
    public static String getSalt(){
        StringBuilder salt = new StringBuilder();
        for(int i =0;i<3;i++){
            int index = (int) (Math.random()*26);
            int num = (int) (Math.random()*10);
            salt.append(PASSWORDSTRING[index]+num+"");
        }
        return salt.toString();
    }
    /**
      * @Author: 贾明祯
      * @Date: 2020/8/17 9:26
      * @introduce: 获取加密和加盐后的密码
      */
    public static String getMD5Str(String password,String salt) {
        byte[] digest = null;
        String str = password+salt;
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest  = md5.digest(str.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (Exception  e) {
            e.printStackTrace();
        }
        //16是表示转换为16进制数
        String md5Str = new BigInteger(1, digest).toString(16);
        return md5Str;
    }

    public static void main(String[] args) {

        String p = "123456";
        User user = new User();
        user.setPassword(PasswordUtil.getMD5Str(p,"N2T8S6"));

        System.out.println(user);
        System.out.println(user.getPassword());
        String newP= "123456";


        String old=PasswordUtil.getMD5Str(newP,"N2T8S6");
        System.out.println(old);
        System.out.println(user.getPassword().equals(old));
    }
}
